package action;

import java.io.ByteArrayInputStream;
import java.io.UnsupportedEncodingException;

import org.json.JSONObject;

import utils.AppConfig;
import utils.AjaxResult;
import utils.HttpsRequest;

public class WechatUserAction extends BaseAction {
    
    private String code;
    
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token";
    private static final String GET_USER_INFO_URL = "https://api.weixin.qq.com/sns/userinfo";
    
    public String userInfo() {
        AjaxResult result;
        
        if (isNullOrEmptyString(code)) {
            result = new AjaxResult(AjaxResult.CODE_ERROR, "参数缺失，获取个人信息失败");
        } else {
            // 构建获取access_token的URL
            StringBuilder builder = new StringBuilder();
            builder.append("appid=").append(AppConfig.APP_ID).append("&")
                    .append("secret=").append(AppConfig.APP_SECRET).append("&")
                    .append("code=").append(code.trim()).append("&")
                    .append("grant_type=authorization_code");
            
            // 发起https请求，获取access_token
            String responseText = null;
            try {
                responseText = HttpsRequest.sendGet(ACCESS_TOKEN_URL, builder.toString());
            } catch (Exception e) {
                responseText = null;
            }
            
            // 处理请求返回的结果
            JSONObject accessTokenResponse = responseText == null ? null : new JSONObject(responseText);
            if (accessTokenResponse != null) {
                String accessToken = accessTokenResponse.has("access_token") ?
                        accessTokenResponse.getString("access_token") : null;
                String openId = accessTokenResponse.has("openid") ?
                        accessTokenResponse.getString("openid") : null;
                if (isNullOrEmptyString(accessToken) || isNullOrEmptyString(openId)) {
                    // 获取失败
                    String errMsg = accessTokenResponse.has("errmsg") ?
                            accessTokenResponse.getString("errmsg") : "Failed to get access_token";
                    result = new AjaxResult(AjaxResult.CODE_ERROR, errMsg);
                    if (accessTokenResponse.has("errcode")) {
                        result.addData("errcode", String.valueOf(accessTokenResponse.getInt("errcode")));
                    }
                } else {
                    // 获取access_token成功
                    // 构建获取用户信息的URL
                    builder = new StringBuilder();
                    builder.append("access_token=").append(accessToken.trim()).append("&")
                            .append("openid=").append(openId).append("&")
                            .append("lang=zh_CN");
                    
                    // 发起https请求
                    String userInfoText = null;
                    try {
                        userInfoText = HttpsRequest.sendGet(GET_USER_INFO_URL, builder.toString());
                    } catch (Exception e) {
                        e.printStackTrace();
                        userInfoText = null;
                    }
                    
                    // 处理请求返回的结果
                    JSONObject userInfoResponse = userInfoText == null ? null : new JSONObject(userInfoText);
                    if (userInfoResponse != null && userInfoResponse.has("openid")) {
                        // 获取成功
                        result = new AjaxResult(AjaxResult.CODE_SUCCESS, "success");
                        // 将返回结果添加到ajax result中
                        String[] keys = { "nickname", "headimgurl", "openid" };
                        for (String key : keys) {
                            if (userInfoResponse.has(key)) {
                                result.addData(key, userInfoResponse.getString(key));
                            }
                        }
                    } else {
                        // 获取失败
                        result = new AjaxResult(AjaxResult.CODE_ERROR, "获取个人信息失败");
                    }
                }
            } else {
                result = new AjaxResult(AjaxResult.CODE_ERROR, "Failed to get access_token");
            }
        }
        
        try {
            inputStream = new ByteArrayInputStream(result.toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
        return SUCCESS;
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

}
